<template>
  <div class="pricing-container">
    <div class="page-header">
      <div class="header-title">
        <h2>计价模型</h2>
        <span class="subtitle">管理运输计价规则和费率</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="openAddModelDialog">
          <el-icon><Plus /></el-icon>添加计价模型
        </el-button>
        <el-button @click="refreshModels">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="模型名称">
          <el-input v-model="filterForm.name" placeholder="请输入模型名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="计价类型">
          <el-select v-model="filterForm.type" placeholder="选择计价类型" clearable>
            <el-option label="按距离计费" value="distance"></el-option>
            <el-option label="按重量计费" value="weight"></el-option>
            <el-option label="按体积计费" value="volume"></el-option>
            <el-option label="按时间计费" value="time"></el-option>
            <el-option label="混合计费" value="mixed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="启用" value="active"></el-option>
            <el-option label="禁用" value="inactive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchModels">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 计价模型列表 -->
    <el-card>
      <el-table
        :data="pricingModels"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="模型名称" min-width="150"></el-table-column>
        <el-table-column prop="type" label="计价类型" width="120">
          <template #default="scope">
            {{ getPricingTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="basePrice" label="基础价格(元)" width="120"></el-table-column>
        <el-table-column prop="unitPrice" label="单位价格" width="120">
          <template #default="scope">
            {{ scope.row.unitPrice }} {{ getPricingUnit(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="minPrice" label="最低收费(元)" width="120"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="editModel(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="viewRules(scope.row)"
            >
              规则详情
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteModel(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalModels"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑计价模型对话框 - 基本结构 -->
    <el-dialog
      v-model="modelDialogVisible"
      :title="isEditMode ? '编辑计价模型' : '添加计价模型'"
      width="650px"
    >
      <el-form
        ref="modelFormRef"
        :model="modelForm"
        :rules="modelRules"
        label-width="100px"
      >
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="modelForm.name" placeholder="请输入模型名称"></el-input>
        </el-form-item>
        <el-form-item label="计价类型" prop="type">
          <el-select v-model="modelForm.type" placeholder="选择计价类型" style="width: 100%">
            <el-option label="按距离计费" value="distance"></el-option>
            <el-option label="按重量计费" value="weight"></el-option>
            <el-option label="按体积计费" value="volume"></el-option>
            <el-option label="按时间计费" value="time"></el-option>
            <el-option label="混合计费" value="mixed"></el-option>
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基础价格" prop="basePrice">
              <el-input-number v-model="modelForm.basePrice" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位价格" prop="unitPrice">
              <el-input-number v-model="modelForm.unitPrice" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最低收费" prop="minPrice">
              <el-input-number v-model="modelForm.minPrice" :min="0" :precision="2" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="modelForm.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="modelForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模型描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="modelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveModel">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)

// 计价模型列表
const pricingModels = ref([
  {
    id: 1,
    name: '标准公里计费',
    type: 'distance',
    basePrice: 50,
    unitPrice: 2.5,
    minPrice: 50,
    updateTime: '2025-03-10 14:30:00',
    status: 'active',
    description: '按公里数计费的标准模型，适用于城市间运输'
  },
  {
    id: 2,
    name: '重货计费',
    type: 'weight',
    basePrice: 100,
    unitPrice: 0.8,
    minPrice: 100,
    updateTime: '2025-03-08 09:15:00',
    status: 'active',
    description: '按货物重量计费，适用于大宗商品运输'
  },
  {
    id: 3,
    name: '体积计费',
    type: 'volume',
    basePrice: 80,
    unitPrice: 10,
    minPrice: 80,
    updateTime: '2025-03-05 16:45:00',
    status: 'active',
    description: '按货物体积计费，适用于轻泡货物运输'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalModels = ref(pricingModels.value.length)

// 筛选表单
const filterForm = ref({
  name: '',
  type: '',
  status: ''
})

// 计价模型对话框
const modelDialogVisible = ref(false)
const isEditMode = ref(false)
const modelFormRef = ref(null)

// 计价模型表单
const modelForm = ref({
  id: null,
  name: '',
  type: 'distance',
  basePrice: 0,
  unitPrice: 0,
  minPrice: 0,
  status: 'active',
  description: ''
})

// 表单验证规则
const modelRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择计价类型', trigger: 'change' }
  ],
  basePrice: [
    { required: true, message: '请输入基础价格', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单位价格', trigger: 'blur' }
  ],
  minPrice: [
    { required: true, message: '请输入最低收费', trigger: 'blur' }
  ]
}

// 获取计价类型名称
const getPricingTypeName = (type) => {
  const typeMap = {
    'distance': '按距离计费',
    'weight': '按重量计费',
    'volume': '按体积计费',
    'time': '按时间计费',
    'mixed': '混合计费'
  }
  return typeMap[type] || '未知'
}

// 获取计价单位
const getPricingUnit = (type) => {
  const unitMap = {
    'distance': '元/公里',
    'weight': '元/吨',
    'volume': '元/立方米',
    'time': '元/小时',
    'mixed': '元/单位'
  }
  return unitMap[type] || '元'
}

// 搜索模型
const searchModels = () => {
  currentPage.value = 1
  // 实际应用中应该调用API搜索数据
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    name: '',
    type: '',
    status: ''
  }
  searchModels()
}

// 刷新模型
const refreshModels = () => {
  loading.value = true
  
  // 实际应用中应该调用API获取最新数据
  setTimeout(() => {
    loading.value = false
    ElMessage.success('计价模型数据已刷新')
  }, 500)
}

// 打开添加模型对话框
const openAddModelDialog = () => {
  isEditMode.value = false
  modelForm.value = {
    id: null,
    name: '',
    type: 'distance',
    basePrice: 0,
    unitPrice: 0,
    minPrice: 0,
    status: 'active',
    description: ''
  }
  modelDialogVisible.value = true
}

// 编辑模型
const editModel = (model) => {
  isEditMode.value = true
  modelForm.value = JSON.parse(JSON.stringify(model))
  modelDialogVisible.value = true
}

// 查看规则详情
const viewRules = (model) => {
  ElMessage.info(`查看 ${model.name} 的规则详情 - 功能待实现`)
  // 实际应用中应该跳转到规则详情页或打开规则详情对话框
}

// 删除模型
const deleteModel = (model) => {
  ElMessageBox.confirm(
    `确定要删除计价模型 "${model.name}" 吗？`,
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API删除模型
    const index = pricingModels.value.findIndex(item => item.id === model.id)
    if (index !== -1) {
      pricingModels.value.splice(index, 1)
      ElMessage.success('计价模型已删除')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 保存模型
const saveModel = () => {
  modelFormRef.value.validate((valid) => {
    if (valid) {
      if (isEditMode.value) {
        // 编辑模式
        const index = pricingModels.value.findIndex(item => item.id === modelForm.value.id)
        if (index !== -1) {
          const updatedModel = JSON.parse(JSON.stringify(modelForm.value))
          updatedModel.updateTime = new Date().toLocaleString()
          pricingModels.value[index] = updatedModel
          ElMessage.success('计价模型已更新')
        }
      } else {
        // 添加模式
        const newModel = JSON.parse(JSON.stringify(modelForm.value))
        newModel.id = pricingModels.value.length > 0 ? Math.max(...pricingModels.value.map(item => item.id)) + 1 : 1
        newModel.updateTime = new Date().toLocaleString()
        pricingModels.value.push(newModel)
        ElMessage.success('计价模型已添加')
      }
      
      modelDialogVisible.value = false
    } else {
      return false
    }
  })
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(() => {
  // 初始化
  refreshModels()
})
</script>

<style scoped>
.pricing-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
